package com.xingshentech.ugv.operate.module.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.alertview.AlertView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xingshentech.carry.proto.v0.FuelProto;
import com.xingshentech.carry.sync.SyncAdapter;
import com.xingshentech.repository.udpmsg.UdpMessageAdapter;
import com.xingshentech.repository.udpmsg.UdpSendMessageAdapter;
import com.xingshentech.ugv.operate.R;
import com.xingshentech.ugv.operate.base.BaseActivity;
import com.xingshentech.ugv.operate.base.CommonRecyclerAdapter;
import com.xingshentech.ugv.operate.module.app.log.XsLog;
import com.xingshentech.ugv.operate.module.app.warehouse.UpdateVehicleHandler;
import com.xingshentech.ugv.operate.module.bean.AppInfo;
import com.xingshentech.ugv.operate.module.constant.Constants;
import com.xingshentech.ugv.operate.module.listener.OnMultiClickListener;
import com.xingshentech.ugv.operate.module.utils.CommonAdapterKt;
import com.xingshentech.ugv.operate.sdk.SDKAdapter;
import com.xstech.library.rxjavahttp.ApiAddress;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements NetworkUtils.OnNetworkStatusChangedListener {
    @BindView(R.id.iv_wifi_title)
    ImageView iv_wifi_title;
    @BindView(R.id.tv_wifi_select)
    TextView tvWifiSelect;
    @BindView(R.id.iv_car_title)
    ImageView iv_car_title;
    @BindView(R.id.tv_car_select)
    TextView tv_car_select;
    @BindView(R.id.tv_battery_power)
    TextView tvBatteryPower;
    @BindView(R.id.tv_position_valid)
    TextView tvPositionValid;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.tv_model)
    TextView tv_model;
    @BindView(R.id.tv_gps)
    TextView tv_gps;
    @BindView(R.id.iv_lightning)
    ImageView iv_lightning;
    @BindView(R.id.iv_loginout)
    TextView iv_loginout;
    @BindView(R.id.tv_data_gather)
    TextView tv_data_gather;
    Adapter adapter;
    List<AppInfo> mList = new ArrayList<>();
    WifiBroadCastReceiver wifiBroadCastReceiver;
    String wifiIpAddress = "";
    FuelProto.Fuel mFuel;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_main;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 6);
        recycleView.setLayoutManager(gridLayoutManager);
        adapter = new Adapter(this, mList);
        recycleView.setAdapter(adapter);

        showCarOrWifi();
        showCarInfo();

        tv_car_select.setOnClickListener(v -> {
        });

        if (!NetworkUtils.isRegisteredNetworkStatusChangedListener(this)) {
            NetworkUtils.registerNetworkStatusChangedListener(this);
        }
        registerWifiReceiver();

    }

    private void registerWifiReceiver() {
        // 1. 实例化BroadcastReceiver子类 &  IntentFilter
        wifiBroadCastReceiver = new WifiBroadCastReceiver();
        // 2. 设置接收广播的类型
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        // 3. 动态注册：调用Context的registerReceiver（）方法
        registerReceiver(wifiBroadCastReceiver, intentFilter);
    }

    public class WifiBroadCastReceiver extends BroadcastReceiver {
//       https://blog.csdn.net/qq_44368698/article/details/146335454?sharetype=blogdetail&sharerId=146335454&sharerefer=PC&sharesource=qq_44368698&spm=1011.2480.3001.8118
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetInfo != null) {
                    if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        if (NetworkInfo.State.CONNECTED == activeNetInfo.getState()) {
//                            if (wifiConnectDialog != null) {
//                                wifiConnectDialog.ConnectSuccess();
//                            }
                        }
                    }
                }
            }
            if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int linkWifiResultError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                if (linkWifiResultError == WifiManager.ERROR_AUTHENTICATING) {
//                    if (wifiConnectDialog != null) {
//                        wifiConnectDialog.PasswordFail();
//                    }
                }
            }

            if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    wifiIpAddress = "";
//                    wifiChangeWareHouseSync("");
//                    XsLog.getInstance().save("broadcast:断开wifi");
                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                        getWifiName();
//                        XsLog.getInstance().save("broadcast:连接wifi");
                    }
                }
            }

            //wifi打开与否
            if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
//                    XsLog.getInstance().save("broadcast:系统关闭wifi");
                } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
//                    XsLog.getInstance().save("broadcast:系统开启wifi");
                }
            }
        }
    }

    /**
     * 显示4g选择车辆还是wifi
     */
    public void showCarOrWifi() {
//        if (Constants.is4gconnect) {
//            iv_car_title.setVisibility(View.VISIBLE);
//            tv_car_select.setVisibility(View.VISIBLE);
//            iv_wifi_title.setVisibility(View.GONE);
//            tvWifiSelect.setVisibility(View.GONE);
//        } else {
//            iv_wifi_title.setVisibility(View.VISIBLE);
//            tvWifiSelect.setVisibility(View.VISIBLE);
//            iv_car_title.setVisibility(View.GONE);
//            tv_car_select.setVisibility(View.GONE);
//        }
    }

    public void showCarInfo() {
        if (Constants.mCarListBean != null) {
            tv_car_select.setText(Constants.mCarListBean.getVehicle().getVehicleName() + "");
        }
    }

    Timer mFaultTimer = new Timer();
    boolean isShowFault = false;

    @Override
    protected void initData() {
//        getTaskBeans(Constants.mAppMenu);
        adapter.notifyDataSetChanged();
//        onVisible(true);

        if (Constants.noNeedLogo == false) {
            mFaultTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String url = ApiAddress.api_center + "baseapi/vehicle/vehicle/alarm/info/listVehicleSpecialFault?vehicleCode=" + Constants.mCarListBean.getVehicle().getIdentifyingCode();
                    Log.e("urlurl", url);
//                    HttpUtils.getInstance().doGet(url, new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//
//                        }
//
//                        @Override
//                        public void onResponse(Call call, Response response) throws IOException {
//                            String jsonData = response.body().string();
//                            Log.e("urlurl", jsonData);
//                            try {
//                                SpecialFaultResponse specialFault = GsonUtils.fromJson(jsonData, SpecialFaultResponse.class);
//                                if (specialFault.isResponseCode()) {
//                                    ThreadUtils.runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//
//                                            if (isShowFault == false) {
//                                                for (SpecialFaultResponse.Data datum : specialFault.getData()) {
//                                                    if (datum.getVehicleAlarmUniqueCode().equals("0x0002310e0071") ||
//                                                            datum.getVehicleAlarmUniqueCode().equals("0x0001310e0071") ||
//                                                            datum.getVehicleAlarmUniqueCode().equals("0x0002310C0071")) {
//
//                                                        isShowFault = true;
//                                                        new AlertView("提示", "控制器连接断开", "确定", null, null,
//                                                                MainActivity.this, AlertView.Style.Alert, (o, position) -> {
//                                                            isShowFault = false;
//                                                        }).setCancelable(false).show();
//
//                                                    }
//                                                }
//
//                                            }
//
//                                        }
//                                    });
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
                }
            }, 0, 5000);
        }

    }



    class Adapter extends CommonRecyclerAdapter<AppInfo> {

        public Adapter(Context context, List<AppInfo> datas) {
            super(R.layout.item_grid_task, datas);
        }

        @Override
        public void convert(BaseViewHolder holder, AppInfo taskBean) {
            ImageView imageView = holder.getView(R.id.iv_task_logo);
            TextView textView = holder.getView(R.id.tv_taskName);
            TextView tvNumberPoint = holder.getView(R.id.tv_number_point);

            imageView.setImageResource(taskBean.getIcon());
            textView.setText(taskBean.getName() + "");
            if (taskBean.getNumber() <= 0) {
                tvNumberPoint.setVisibility(View.INVISIBLE);
            } else {
                tvNumberPoint.setVisibility(View.VISIBLE);
                tvNumberPoint.setText(String.valueOf(taskBean.getNumber()));
            }


            CommonAdapterKt.getItemView(holder).setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View v) {
                    taskBean.getAppOnStart().checkAndStart();
                }
            });
            taskBean.getAppOnStart().init(holder);  //调用初始化接口
        }
    }

    private void getWifiName() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            String ssid = wifiInfo.getSSID();
            String ipAddress = getIpAddress(wifiInfo.getIpAddress());
            String name = ssid.replace("<", "").replace(">", "").replace("\"", "");
            if (!ipAddress.equalsIgnoreCase(wifiIpAddress)) {
                wifiIpAddress = ipAddress;
                //延时一秒是因为wifi监听立马加入 会导致还没分配ip地址
                ThreadUtils.runOnUiThreadDelayed((Runnable) () -> {
                    SyncAdapter.getAdapter().setProgressHandler(UpdateVehicleHandler.getInstance());
//                    XsLog.getInstance().save("delay1000ms,join_Wifi_MulticastSocket");
                }, 1000);
//                XsLog.getInstance().save("wifi_change:" + name + ":" + ipAddress);
            }
//            XsLog.getInstance().save("wifi:" + name + ":" + ipAddress);
            tvWifiSelect.post(() -> tvWifiSelect.setText(name));
        } else {
            tvWifiSelect.post(() -> tvWifiSelect.setText(""));
        }

    }

    private String getIpAddress(int ipAddress) {
        String ipString = "";// 本机在WIFI状态下路由分配给的IP地址
        if (ipAddress != 0) {
            ipString = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                    + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
        }
        return ipString;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        SDKAdapter.getInstance().disconnect();
        if (wifiBroadCastReceiver != null) {
            unregisterReceiver(wifiBroadCastReceiver);
        }
        NetworkUtils.unregisterNetworkStatusChangedListener(this);
        UdpSendMessageAdapter.getAdapter().close();
        UdpMessageAdapter.getAdapter().close();
//        if (mFaultTimer != null) {
//            mFaultTimer.cancel();
//        }
    }

    @Override
    public void onDisconnected() {
//        XsLog.getInstance().save("onDisconnected");
    }

    @Override
    public void onConnected(NetworkUtils.NetworkType networkType) {
//        XsLog.getInstance().save("onConnected:" + networkType.name());
    }
}